<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>用 Prototype 添加错误处理</title>
    <style>
        .fieldname,
        .submit {
            text-align: right;
        }
    </style>
</head>
<body>
<form name="login">
    <table>
        <tr>
            <td class="fieldname">Username:</td>
            <td><label for="username"><input id="username" type="text"></label></td>
            <td><a id="username-availability" href="#">Check Availability</a></td>
        </tr>
        <tr>
            <td class="fieldname">Email:</td>
            <td><label for="email"><input id="email" type="email"></label></td>
            <td><a id="email-availability" href="#">Check Availability</a></td>
        </tr>
        <tr>
            <td class="fieldname">Password:</td>
            <td><label for="password"><input id="password" type="password"></label></td>
        </tr>
        <tr>
            <td class="fieldname">Verify Password:</td>
            <td><label for="verify-passowrd"><input id="verify-passowrd" type="password"></label></td>
        </tr>
        <tr>
            <td class="submit" colspan="2"><label for="submit"><input id="submit" type="submit"></label></td>
            <td></td>
        </tr>
    </table>
</form>
<script src="//cdn.bootcss.com/prototype/1.7.3/prototype.min.js"></script>
<script>
    function checkUsername(e) {
        e.preventDefault();
        var username = $('username').value;
        if (!username) {
            alert('Please enter a user name to check!');
            return;
        }
        var options = {
            method: 'get',
            onSuccess: handleResponse,
            onFailure:handleError,
            parameters: {username: username}
        };
        new Ajax.Request('form-validator.php', options);
    }

    function checkEmail(e) {
        e.preventDefault();
        var email = $('email').value;
        if (!email) {
            alert('Please enter an email to check!');
            return;
        }
        var options = {
            method: 'get',
            onSuccess: handleResponse,
            onFailure:handleError,
            parameters: {email: email}
        };
        new Ajax.Request('form-validator.php', options);
    }

    function handleResponse(transport) {
        var obj = transport.responseJSON;
        if (obj.available) {
            alert(obj.searchTerm + ' is available!');
        } else {
            alert('We\'re sorry, but ' + obj.searchTerm + ' is not available.');
        }
    }

    function handleError() {
        alert('A network error occurred. Please try again in a few monents.');
    }

    $('username-availability').observe('click', checkUsername);
    $('email-availability').observe('click', checkEmail);
</script>
</body>
</html>